package com.sqx.modules.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.AliPayService;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.stockManage.dao.StockManageDao;
import com.sqx.modules.stockManage.entity.StockManage;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.tbOrders.service.TbOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值记录
 */
@Service
public class PayDetailsServiceImpl extends ServiceImpl<PayDetailsDao, PayDetails> implements PayDetailsService {

    /**
     * 充值记录
     */
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private WxService wxService;
    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private TbOrdersService orderService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private TbCouponUserService tbCouponUserService;
    @Autowired
    private StockManageDao stockManageDao;

    @Override
    public PageUtils selectPayDetails(int page, int limit, String startTime, String endTime, Long userId,
                                      Integer state, String phone, String userName, String orderId, Integer classify) {
        Page<Map<String, Object>> pages = new Page<>(page, limit);
        if (state != null && state == -1) {
            state = null;
        }
        return new PageUtils(payDetailsDao.selectPayDetails(pages, startTime, endTime, userId, state, phone, userName, orderId, classify));
    }

    @Override
    public Double selectSumPay(String createTime, String endTime, Long userId) {
        if (userId == null || userId == -1) {
            return payDetailsDao.selectSumPay(createTime, endTime, null);
        }
        return payDetailsDao.selectSumPay(createTime, endTime, userId);
    }


    @Override
    public Double selectSumMember(String time, Integer flag) {
        return payDetailsDao.selectSumMember(time, flag);
    }

    @Override
    public Double selectSumPayByState(String time, Integer flag, Integer state) {
        return payDetailsDao.selectSumPayByState(time, flag, state);
    }

    @Override
    public Double selectSumPayByClassify(String time, Integer flag, Integer classify, Integer payClassify) {
        return payDetailsDao.selectSumPayByClassify(time, flag, classify, payClassify);
    }

    @Override
    public Double instantselectSumPay(String date, Long userId) {
        return payDetailsDao.instantselectSumPay(date, userId);
    }

    @Override
    public HashMap<String, Object> payMessage(String date, Integer type) {

        HashMap<String, Object> hashMap = new HashMap<>();
        //总金额
        BigDecimal allMoney = payDetailsDao.payMessage(date, type, null);
        //微信app支付
        BigDecimal appMoney = payDetailsDao.payMessage(date, type, 1);
        //微信公众号支付
        BigDecimal wxRwmMoney = payDetailsDao.payMessage(date, type, 2);
        //微信小程序支付
        BigDecimal wxAppMoney = payDetailsDao.payMessage(date, type, 3);
        //支付宝app支付
        BigDecimal zfbMoney = payDetailsDao.payMessage(date, type, 4);
        //支付宝H5支付
        BigDecimal zfbH5Money = payDetailsDao.payMessage(date, type, 5);
        //零钱支付
        BigDecimal lqMoney = payDetailsDao.payMessage(date, type, 6);
        //管理后台充值支付
        BigDecimal sysMoney = userMoneyDetailsDao.payMessage(date, type);
        // 已退款金额
        BigDecimal refundMoney = userMoneyDetailsDao.payMessageByRefund(date, type);
        // 统计回收商品的利润
        BigDecimal totalProfit = BigDecimal.ZERO; // 初始化总利润为0
        List<StockManage> stockManages = stockManageDao.selectListByStockManage(date,type);
        if (!stockManages.isEmpty()) {
            for (StockManage stockManage : stockManages) {
                // 回收价格总数
                BigDecimal profitMoney = BigDecimal.ZERO;
                // 出售价格总数
                BigDecimal sellMoney = BigDecimal.ZERO;
                // 判断库存和出库数量(如果全部售出)
                if (stockManage.getStock() == 0 && stockManage.getOutStock() > 0) {
                    // 算出回收价格利
                    profitMoney = stockManage.getPutPrice().multiply(BigDecimal.valueOf(stockManage.getOutStock()));
                    // 算出售出价格利
                    sellMoney = stockManage.getOutPrice().multiply(BigDecimal.valueOf(stockManage.getOutStock()));
                    // 判断库存和出库数量(如果一件还未出售)
                } else if (stockManage.getStock() > 0 && stockManage.getOutStock() == 0) {
                    // 算出回收价格利
                    profitMoney = stockManage.getPutPrice().multiply(BigDecimal.valueOf(stockManage.getStock()));
                    // 算出售出价格利
                    sellMoney = stockManage.getOutPrice().multiply(BigDecimal.valueOf(stockManage.getOutStock()));
                    // 判断库存和出库数量(如果有未售出和未出售)
                } else if (stockManage.getStock() > 0 && stockManage.getOutStock() > 0) {
                    // 算出回收价格利
                    profitMoney = stockManage.getPutPrice().multiply(BigDecimal.valueOf(stockManage.getStock()));
                    // 算出售出价格利
                    sellMoney = stockManage.getOutPrice().multiply(BigDecimal.valueOf(stockManage.getOutStock()));
                }
                // 计算该商品的利润（卖出价格 - 回收成本）
                BigDecimal profitForThisItem = sellMoney.subtract(profitMoney);
//                if (profitForThisItem.compareTo(BigDecimal.ZERO) <= 0) {
//                    profitForThisItem = BigDecimal.ZERO;
//                }
                // 将该商品的利润添加到总利润中
                totalProfit = totalProfit.add(profitForThisItem);
            }
        }

        hashMap.put("allMoney", allMoney);
        hashMap.put("appMoney", appMoney);
        hashMap.put("wxRwmMoney", wxRwmMoney);
        hashMap.put("wxAppMoney", wxAppMoney);
        hashMap.put("zfbMoney", zfbMoney);
        hashMap.put("zfbH5Money", zfbH5Money);
        hashMap.put("lqMoney", lqMoney);
        hashMap.put("sysMoney", sysMoney);
        hashMap.put("refundMoney", refundMoney);
        hashMap.put("totalProfit", totalProfit);
        return hashMap;


    }


    @Override
    public Result refundPayDetails(Long payId, Long orderId) {
        TbOrders order = orderService.getById(orderId);
        PayDetails payDetails = baseMapper.selectOne(new QueryWrapper<PayDetails>().eq("order_id", order.getOrderNumber()));
        if ((order.getStatus() == 1 || order.getStatus() == 2 || order.getStatus() == 3 || order.getStatus() == 4) && order.getIsPay() == 1 && payDetails.getState() == 1) {
            if (payDetails.getClassify() == 1 || payDetails.getClassify() == 2 || payDetails.getClassify() == 3 || payDetails.getClassify() == 7) {
                if (wxService.refund(payDetails.getOrderId(), null)) {
                    //用户退款，将上级收益退回
                    order.setStatus(5);
                    orderService.updateById(order);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(order.getBuyerId());
                    userMoneyDetails.setTitle("退款成功订单：" + order.getOrderNumber());
                    userMoneyDetails.setContent("退款金额：" + payDetails.getMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setClassify(4);
                    userMoneyDetails.setMoney(order.getTotalPrice());
                    userMoneyDetails.setRelationId(order.getOrderId());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetailsDao.insert(userMoneyDetails);
                    Goods goods = goodsDao.selectById(order.getGoodId());
                    if(goods != null && goods.getStockId() != null){
                        goods.setStock(goods.getStock() + order.getBuyNum());
                        goods.setIsEnable(1);
                    }else if (goods != null && goods.getIsStock() != null && goods.getIsStock() == 2) {
                        goods.setStock(goods.getStock() + order.getBuyNum());
                        goods.setIsEnable(1);
                    }
                    goodsDao.updateById(goods);
                    // 将优惠券设置为未使用状态
                    if (order.getCouponId() != null) {
                        TbCouponUser tbCouponUser = tbCouponUserService.getById(order.getCouponId());
                        if (tbCouponUser != null) {
                            tbCouponUser.setStatus(0);
                        }
                        tbCouponUserService.updateById(tbCouponUser);
                    }
                    return Result.success("退款成功");
                } else {
                    return Result.error("退款异常,请重试");
                }
            } else if (payDetails.getClassify() == 4 || payDetails.getClassify() == 5) {
                if (aliPayService.aliRefund(payDetails.getOrderId(), null)) {
                    //用户退款，将上级收益退回
                    order.setStatus(5);
                    orderService.updateById(order);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(order.getBuyerId());
                    userMoneyDetails.setTitle("退款成功订单：" + order.getOrderNumber());
                    userMoneyDetails.setContent("退款金额：" + payDetails.getMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setMoney(order.getTotalPrice());
                    userMoneyDetails.setClassify(4);
                    userMoneyDetails.setRelationId(order.getOrderId());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetailsDao.insert(userMoneyDetails);
                    Goods goods = goodsDao.selectById(order.getGoodId());
                    if(goods != null && goods.getStockId() != null){
                        goods.setStock(goods.getStock() + order.getBuyNum());
                        goods.setIsEnable(1);
                    }else if (goods != null && goods.getIsStock() != null && goods.getIsStock() == 2) {
                        goods.setStock(goods.getStock() + order.getBuyNum());
                        goods.setIsEnable(1);
                    }
                    goodsDao.updateById(goods);
                    // 将优惠券设置为未使用状态
                    if (order.getCouponId() != null) {
                        TbCouponUser tbCouponUser = tbCouponUserService.getById(order.getCouponId());
                        if (tbCouponUser != null) {
                            tbCouponUser.setStatus(0);
                        }
                        tbCouponUserService.updateById(tbCouponUser);
                    }
                    return Result.success("退款成功");
                } else {
                    return Result.error("退款异常,请重试");
                }
            } else {
                UserEntity userEntity = userDao.selectById(order.getBuyerId());
                if (userEntity != null) {
                    userEntity.setBalance(userEntity.getBalance().add(order.getTotalPrice()));
                    userDao.updateById(userEntity);
                    //用户退款，将上级收益退回
                    order.setStatus(5);
                    orderService.updateById(order);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(order.getBuyerId());
                    userMoneyDetails.setTitle("退款成功订单：" + order.getOrderNumber());
                    userMoneyDetails.setContent("退款金额：" + payDetails.getMoney());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setMoney(order.getTotalPrice());
                    userMoneyDetails.setClassify(4);
                    userMoneyDetails.setRelationId(order.getOrderId());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                    userMoneyDetailsDao.insert(userMoneyDetails);
                    Goods goods = goodsDao.selectById(order.getGoodId());
                    if(goods != null && goods.getStockId() != null){
                        goods.setStock(goods.getStock() + order.getBuyNum());
                        goods.setIsEnable(1);
                    }else if (goods != null && goods.getIsStock() != null && goods.getIsStock() == 2) {
                        goods.setStock(goods.getStock() + order.getBuyNum());
                        goods.setIsEnable(1);
                    }
                    goodsDao.updateById(goods);
                    // 将优惠券设置为未使用状态
                    if (order.getCouponId() != null) {
                        TbCouponUser tbCouponUser = tbCouponUserService.getById(order.getCouponId());
                        if (tbCouponUser != null) {
                            tbCouponUser.setStatus(0);
                        }
                        tbCouponUserService.updateById(tbCouponUser);
                    }
                    return Result.success("退款成功");
                } else {
                    return Result.error("退款用户不存在，请检查");
                }
            }
        }
        return Result.error("退款异常,请重试");
    }

    @Override
    public Result refundPayDetailsByUserId(Long userId, Long payId) {
        PayDetails payDetails = baseMapper.selectOne(new QueryWrapper<PayDetails>()
                .eq("user_id", userId)
                .eq("id", payId));
        if (payDetails.getClassify() == 1 || payDetails.getClassify() == 2 || payDetails.getClassify() == 3 || payDetails.getClassify() == 7) {
            if (wxService.refund(payDetails.getOrderId(), null)) {
                //用户退款，将上级收益退回
//                orderService.setCommission(Long.valueOf(payDetails.getOrderId()), 2);
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(payDetails.getUserId());
                userMoneyDetails.setTitle("退款成功");
                userMoneyDetails.setContent("退款金额：" + payDetails.getMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(4);
                userMoneyDetails.setRelationId(payDetails.getId());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetailsDao.insert(userMoneyDetails);
                return Result.success("退款成功");
            } else {
                return Result.error("退款异常,请重试");
            }
        } else {
            if (aliPayService.aliRefund(payDetails.getOrderId(), null)) {
                //用户退款，将上级收益退回
//                orderService.setCommission(Long.valueOf(payDetails.getOrderId()), 2);
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(payDetails.getUserId());
                userMoneyDetails.setTitle("退款成功");
                userMoneyDetails.setContent("退款金额：" + payDetails.getMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(4);
                userMoneyDetails.setRelationId(payDetails.getId());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetailsDao.insert(userMoneyDetails);
                return Result.success("退款成功");
            } else {
                return Result.error("退款异常,请重试");
            }
        }
    }
}
